package cn.wjx.taobaounion.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wjx.taobaounion.R;
import cn.wjx.taobaounion.base.BaseActivity;
import cn.wjx.taobaounion.model.domain.TicketResult;
import cn.wjx.taobaounion.presenter.ITicketPresenter;
import cn.wjx.taobaounion.ui.custom.LoadingView;
import cn.wjx.taobaounion.utils.LogUtils;
import cn.wjx.taobaounion.utils.PresenterManger;
import cn.wjx.taobaounion.utils.ToastUtil;
import cn.wjx.taobaounion.utils.URLUtils;
import cn.wjx.taobaounion.view.ITicketPageCallback;

/**
 * @author WuChangJian
 * @date 2020/6/22 20:21
 */
public class TicketActivity extends BaseActivity implements ITicketPageCallback {

    private ITicketPresenter mTicketPresenter;
    private boolean mHasTaobao = false;
    @BindView(R.id.ticket_back_press)
    public ImageView backPress;
    @BindView(R.id.ticket_cover)
    public ImageView ticketCover;
    @BindView(R.id.ticket_code)
    public EditText ticketCode;
    @BindView(R.id.ticket_loading_view)
    public LoadingView mLoadingView;
    @BindView(R.id.ticket_open_copy)
    public TextView openOrCopyTicket;
    @BindView(R.id.ticket_network_error)
    public TextView ticketNetworkError;
    @OnClick(R.id.ticket_network_error)
    public void retry() {
        // 网络错误加载重试
        if (ticketNetworkError != null) {
            ticketNetworkError.setVisibility(View.GONE);
        }
        if (mTicketPresenter != null) {
            Intent intent = getIntent();
            if (intent != null) {
                String title = intent.getStringExtra("title");
                String url = intent.getStringExtra("url");
                String cover = intent.getStringExtra("cover");
                mTicketPresenter.getTicket(title, cover, url);
            }
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ticket;
    }

    @Override
    protected void initEvent() {
        backPress.setOnClickListener(v -> {
            finish();
        });
        openOrCopyTicket.setOnClickListener(v -> {
            // 获取淘口令将内容复制进剪切板
            String code = ticketCode.getText().toString().trim();
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("tao_bao_union", code);
            cm.setPrimaryClip(clipData);
            LogUtils.d(TicketActivity.this, code);
            // 判断手机是否有淘宝应用
            if (!mHasTaobao) {
                ToastUtil.showToast("已经复制,黏贴分享,或打开淘宝");
            } else {
                // 跳转到淘宝
                Intent intent = new Intent();
                ComponentName componentName = new ComponentName("com.taobao.taobao", "com.taobao.tao.TBMainActivity");
                intent.setComponent(componentName);
                startActivity(intent);
            }

        });
    }

    @Override
    protected void initPresenter() {
        mTicketPresenter = PresenterManger.getInstance().getTicketPresenter();
        mTicketPresenter.registerViewCallback(this);
        // 判断是否有淘宝应用，android下每个app都会有唯一的applicationId，
        //  比如本应用，build.gradle -->app android defaultConfig applicationId "cn.wjx.taobaounion"
        // 判断本机是否有淘宝的application id，adb shell logcat | grep START
        // {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000
        // hwFlg=0x10
        // cmp=com.taobao.taobao/com.taobao.tao.welcome.Welcome bnds=[540,656][793,942]}
        PackageManager pm = getPackageManager();
        try {
            PackageInfo pkInfo = pm.getPackageInfo("com.taobao.taobao", PackageManager.MATCH_UNINSTALLED_PACKAGES);
            if (pkInfo != null) {
                mHasTaobao = true;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            mHasTaobao = false;
        }
        openOrCopyTicket.setText(mHasTaobao ? "打开淘宝领券" : "复制淘口令");
    }

    @Override
    public void onTicketLoaded(String cover, TicketResult ticket) {
        if (!TextUtils.isEmpty(cover)) {
            String targetPath = URLUtils.getTicketPath(cover);
            Glide.with(this).load(targetPath).into(ticketCover);
        } else {
            ticketCover.setImageResource(R.mipmap.placehoder_pic);
        }
        if (ticket != null && ticket.getData().getTbk_tpwd_create_response() != null) {
            ticketCode.setText(ticket.getData().getTbk_tpwd_create_response().getData().getModel());
        }
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onError() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
        if (ticketNetworkError != null) {
            ticketNetworkError.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
        if (ticketNetworkError != null) {
            ticketNetworkError.setVisibility(View.GONE);
        }
    }

    @Override
    public void onEmpty() {

    }

    @Override
    protected void release() {
        mTicketPresenter.unregisterViewCallback(this);
    }
}
